class BlogEntry < ActiveRecord::Base
  ITEMS_PER_PAGE = 8
  
  has_many  :tags,     :through => :taggings
  has_many  :taggings, :as => :taggable
  has_many  :comments, :as => :commentable, :conditions => ['published = ?', '1'], :dependent => :destroy
  has_many  :attachments, :as => :attachee
  
  after_validation :add_canonical_title
  
  def self.get_items(count = ITEMS_PER_PAGE, page = nil, tag = nil)
    page = cleaned_page(page)
    
    if tag
      find_by_tag(tag, count, page)
    else
      find(
        :all,
        :conditions => {
          :published  => true
        },
        :offset     => (page - 1) * count,
        :limit      => count,
        :order      => "created_at DESC"
      )
    end
  end
  
  def self.get_counts(page_size = ITEMS_PER_PAGE, tag = nil)
    if tag
      count_by_tag(tag, count)
    else
      counts = 
        count(
          :conditions => {
            :published => true
          })
      pages = ((counts - 1)/ page_size) + 1
      [counts, pages]
    end
  end
  
  def self.find_by_tag(tag_name, count = ITEMS_PER_PAGE, page = nil)
    page = cleaned_page(page)

    tag = 
      Tag.find(:first,
        :conditions => {
          :name => tag_name})
    
    if tag 
      taggables = 
        Tagging.find(
          :all,
          :conditions => {
            :tag_id => tag.id,
            :taggable_type => "BlogEntry"
          },
          :offset     => (page - 1) * count,
          :limit      => count,
          :order      => "id DESC",
          :include    => :taggable
        ).collect { |tagging|
            tagging.taggable
        }
    else
      []
    end
  end
  
  def self.count_by_tag(tag_name, count = ITEMS_PER_PAGE)
    tag = 
      Tag.find(:first,
        :conditions => {
          :name => tag_name})
    
    if tag 
      counts = 
        Tagging.count(
          :conditions => {
            :tag_id => tag.id,
            :taggable_type => "BlogEntry"
          }
        )
      pages = ((counts - 1)/ count) + 1
      [counts, pages]
    else
      [0, 0]
    end
  end
  
  def remove_tags
    self.taggings.each do |tagging|
      tagging.delete
    end
    self.taggings = []
  end
  
  def remove_attachments
    self.attachments.each do |attachment|
      attachment.delete
    end
    self.attachments = []
  end
  
  def add_canonical_title
    self.canonical_title = "#{self.title.canonize}"
  end
  
end
